<?php
namespace App\Http\Services;

use App\Http\Model\FinanceUserWallet;
use App\Http\Model\Hint;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use App\Lib\Search;
use App\Http\Services\ApiServices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ChatFriendServices extends CommonServices
{
    protected $union_user_model;//公会成员表
    protected $union_model;//公会表
    protected $user_model;//用户资料表
    protected $finance_user_wallet_model;//用户财富表
    protected $userTagService;

    protected $EsSearch;
    protected $apiService;
    protected $logion_log = 'user_login_log';//登录表
    protected $chat_friend_baseinfo_table = 'chat_friend_baseinfo';//用户审核资料表
    protected $liveTime = 2;//主播直播总时长(小时)
    protected $anchorLiveTime = 'MICLIVETIME:USER:';//主播总开播时长 string
    protected $userAlreadyShow = 'USERALREADY:SHOW:';//用户显示过的搜索结果 string
    protected $user_fulsh_data = 'USERFLUSH:CHAT:FRIEND:';//用户刷新次数
    protected $newPage = 'NEWPAGE:CHAT:FRIEND';//为了解决刷新为空的问题重新生成page.

    public function __construct()
    {
        $this->union_user_model = new UnionUser();
        $this->union_model = new Union();
        $this->EsSearch = new Search();
        $this->user_model = new User();
        $this->finance_user_wallet_model = new FinanceUserWallet();
        $this->userTagService = new UserTagServices();
        $this->apiService = new ApiServices();
    }

    //获取用户资料是否齐全非主播不验证
    public function checkUserBaseInfo($userInfo){
        //获取用户身份
        $userType = $this->getUserBlongToUinon($userInfo['user_id']);
        $code = Hint::SUCCESS;
        $msg = 'ok';
        $data = [
            'user_type' => 1, //1用户2主播
            'base_info_status' => 1 //1齐全0不齐全
        ];
        
        do{
            if($userType){
                $data['user_type'] = 2; //主播
                //主播身份获取基本配置信息,是否有照片上传，是否有语音介绍，是否有个人资料 并且审核通过的
                $status = $this->user_model->getChatFriendVerify($userInfo['user_id']);
                //获取主播交友快捷语
                $data['chat_sign'] = empty($status['chat_sign']) ? '' : $status['chat_sign'];
                if(empty($status['chat_sign'])){
                    $data['base_info_status'] = 0;
                    break;
                }
                if(empty($status)){
                    $data['base_info_status'] = 0;
                    break;
                }
                if($status['status'] != 1){
                    $data['base_info_status'] = 0;
                    break;
                }
                if(empty($userInfo['thumbnails'])){
                    $data['base_info_status'] = 0;
                    break;
                }
                //是否有语音
                if(empty($userInfo['voice'])){
                    $data['base_info_status'] = 0;
                    break;
                }
                //是否有个人简介或者标签
                if(empty($userInfo['sign']) || empty($userInfo['tags'])){
                    $data['base_info_status'] = 0;
                    break;
                }
                
            }
        }while(false);
        return compact('code','data','msg');
    }

    //获取成员所属公会
    public function getUserBlongToUinon($userId){
        $res = $this->union_user_model->userToUnion($userId);
        if(!empty($res)){
            //查看公会是否认证
            $checkStatus = $this->union_model->getUnions([$res['un_id']]);
            if(isset($checkStatus[0]['authentication_status']) && $checkStatus[0]['authentication_status'] != 0){
                return $checkStatus;
            }
        }
        return false;
    }

    //查看用户基本资料以及审核状态
    public function getVerify($userId){
        $status = $this->user_model->getChatFriendVerify($userId);
        if(empty($status)){
            return [];
        }
        return $status;
    }
    //获取交友列表
    public function getListData($page,$limit,$userId){
        //用户身份
        $userType = $this->getUserBlongToUinon($userId);

            do{
                $code = Hint::SUCCESS;
                $list = [];
                $msg = 'ok';
                if(!empty($userType)){
                    //主播身份查看上麦时间是否大于等于规定的时间,不满足

                    //的情况下显示在线主播逻辑
                    $liveTime = empty(Redis::get($this->anchorLiveTime.$userId)) ? 0 : Redis::get($this->anchorLiveTime.$userId);

                    $liveHour = $liveTime/3600;
                    if($liveHour >= $this->liveTime){
                        //缓存1分钟只能刷5次
                        if(!redis_num_lock($this->user_fulsh_data.$userId, 60, 5)){
                            $code = Hint::NOT_FREQ;
                            $msg = '刷新太频繁';
                            break;
                        }

                        $list = $this->showUserList($page,$limit,$userId);

                    }else{
                    $list = $this->showAnchorList($page,$limit,$userId);

                    }
                }else{
                    $list = $this->showAnchorList($page,$limit,$userId);

                }

                if(!empty($list['list'])) {
                    foreach($list['list'] as $key=>$val) {
//                        $val['sign'] = empty($val['sign']) ? '该用户暂时还没有简介！' : $val['sign'];
                        $val['sign'] = empty($val['sign']) ? '' : $val['sign'];
                        $list['list'][$key] = $val;
                    }
                }

            }while(false);


        return compact('code','list','msg');
    }

    //获取主播列表
    public function showAnchorList($page,$limit,$userId){
        //查询登录用户的基本信息
        $userInfo = $this->user_model->get_user($userId,false);

        if(empty($userInfo)){
            return [];
        }
        //性别
        $gender = in_array($userInfo['gender'],[1,2]) ? $userInfo['gender'] : 1;
        //显示主播列表
        $query = [
            'bool' => [
                'filter'=>[
                    "term"=>[
                        "gender"=>$gender == 1 ? 2 : 1 , //1=男显示女的 2=女的显示男的
                    ],
                ],
            ]
        ];
        $sort = [
            "charm_balance"=>array('order'=>'desc')
        ];
        $res = $this->EsSearch->getSearchData('chat_friend_anchor_user','user',$limit,$page-1,$query);

        if($res['total'] != 0 ){
            if(count($res['data']) == 0){

                $res = $this->getAnchorData($limit,$query,$sort,$userId);
            }else{
                Redis::DEL($this->newPage.$userId);
            }
        }
        if(!empty($res['data'])){
            $userIds = array_column($res['data'],'user_id');
            $liveArr = $this->apiService->liveRooms($userIds);
            foreach($res['data'] as $k=>&$v){
                unset($tagList);
                $imgArr = json_decode($v['portrait'],true);
                $v['portrait'] = array_map(function($key){return build_image($key);},$imgArr);
                $v['birthday'] = date('Y-m-d',$v['birthday']);
                $v['voice'] = build_url($v['voice']);
                if(!empty($v['tags'])){
                    //标签信息
                    $tagInfo = $this->userTagService->getTagNames(json_decode($v['tags'],true));
                    foreach($tagInfo as $keys=>$tag){
                        $tagList[] = ['name'=>$tag,'tag_id'=>$keys];
                    }
                    $v['tags'] = $tagList;
                }else{
                    $v['tags'] = [];
                }
                $v['is_online'] = $v['is_online'];
                //获取用户直播状态
                if(isset($liveArr[$v['user_id']]) && !empty($liveArr[$v['user_id']])){
                    $v['live_room_id'] = $liveArr[$v['user_id']];
                }else{
                    $v['live_room_id'] = 0;
                }

            }

        }
        $data['is_user_list'] = 2; //主播
        $data['list'] = $res['data'];
        return $data;
    }

    //获取用户列表
    public function showUserList($page,$limit,$userId){
        $userInfo = $this->user_model->get_user($userId,false);

        if(empty($userInfo)){
            return [];
        }
        //性别
        $gender = in_array($userInfo['gender'],[1,2]) ? $userInfo['gender'] : 1;
        //查看已经显示过的用户
	    $alreadyShow = Redis::get($this->userAlreadyShow.$userId);
//	    $alreadyShow = false;
        if(empty($alreadyShow)){

//            $query = [
//                'match_all' => new \stdClass()
//            ];
            $query = [
                'bool' => [
                    'filter'=>[
                        "term"=>[
                            "gender"=>$gender == 1 ? 2 : 1 , //1=男显示女的 2=女的显示男的
                        ],
                    ],
                ]
            ];
        }else{
            //处理已经显示过的用户
            $query = [
                'bool' => [
                    'must_not' => [
                        'terms' => [
                            'user_id' => explode(',',$alreadyShow),

                        ]
                    ]
                ]
            ];
        } 
        $res = $this->EsSearch->getSearchData('chat_friend_user','user',$limit,$page-1,$query);

        if(!empty($res['data'])){
            foreach($res['data'] as $k=>&$v){
                unset($tagList);
                $imgArr = json_decode($v['portrait'],true);
                $v['portrait'] = array_map(function($key){return build_image($key);},$imgArr);
                $v['birthday'] = date('Y-m-d',$v['birthday']);
                $v['live_room_id'] = 0;
                $v['is_online'] = 0;
                if(!empty($v['tags'])){
                    //标签信息
                    $tagInfo = $this->userTagService->getTagNames(json_decode($v['tags'],true));
                    foreach($tagInfo as $keys=>$tag){
                        $tagList[] = ['name'=>$tag,'tag_id'=>$keys];
                    }
                    $v['tags'] = $tagList;
                }else{
                    $v['tags'] = [];
                }
                if(!empty($v['voice'])){
                    $v['voice'] = build_url($v['voice']);
                }
            }
            //储存已经显示过的用户
            $user_ids = array_column($res['data'],'user_id');
            $user_ids_str = implode(',',$user_ids);
            if(!empty($alreadyShow)){
                $user_ids_str = $user_ids_str.','.$alreadyShow;
            }
            Redis::set($this->userAlreadyShow.$userId,$user_ids_str);
            Redis::expire($this->userAlreadyShow.$userId,3600*3);//3小时
        }
        $data['is_user_list'] = 1;
        $data['list'] = $res['data'];
        return $data;
    }

    //为了解决前端不显示空数据,从1开始获取数据
    public function getAnchorData($limit,$query,$sort,$userId){

        $page = empty(Redis::get($this->newPage.$userId)) ? 1 :  Redis::get($this->newPage.$userId);
        if($page == 1){
            Redis::INCRBY($this->newPage.$userId,1);
        }
        $res = $this->EsSearch->getSearchData('chat_friend_anchor_user','user',$limit,$page-1,$query,$sort);
        //设置自增page
        if(count($res['data']) == 0){
            Redis::DEL($this->newPage.$userId);
            $res = $this->getAnchorData($limit,$query,$sort,$userId);
        }else{
            Redis::INCRBY($this->newPage.$userId,1);
        }
        return $res;
    }
//    public function getListData2($page,$limit,$userId){
//        //用户身份
//        $userType = $this->getUserBlongToUinon($userId);
//
//        do{
//            $code = Hint::SUCCESS;
//            $list = [];
//            $msg = 'ok';
//            if(!empty($userType)){
//                //主播身份查看上麦时间是否大于等于规定的时间,不满足的情况下显示在线主播逻辑
//                $liveTime = empty(Redis::get($this->anchorLiveTime.$userId)) ? 0 : Redis::get($this->anchorLiveTime.$userId);
//
//                $liveHour = $liveTime/3600;
//
//                if($liveHour >= $this->liveTime){
//                    //缓存1分钟只能刷5次
//                    if(!redis_num_lock($this->user_fulsh_data.$userId, 60, 5)){
//                        $code = Hint::NOT_FREQ;
//                        $msg = '刷新太频繁';
//                        break;
//                    }
//                    $list = $this->showUserList2($page,$limit,$userId);
//
//                }else{
//                    $list = $this->showAnchorList($page,$limit,$userId);
//
//                }
//            }else{
//                $list = $this->showAnchorList($page,$limit,$userId);
//
//            }
//            if(!empty($list['list'])) {
//                foreach($list['list'] as $key=>$val) {
//                    $val['sign'] = empty($val['sign']) ? '该用户暂时还没有简介！' : $val['sign'];
//                    $list['list'][$key] = $val;
//                }
//            }
//
//        }while(false);
//
//
//        return compact('code','list','msg');
//    }
//    public function showUserList2($page,$limit,$userId){
//        $userInfo = $this->user_model->get_user($userId,false);
//
//        if(empty($userInfo)){
//            return [];
//        }
//        //性别
//        $gender = in_array($userInfo['gender'],[1,2]) ? $userInfo['gender'] : 1;
//
//        //查看已经显示过的用户
//        $alreadyShow = Redis::get($this->userAlreadyShow.$userId);
////        $alreadyShow = false;
////        unset($alreadyShow);
//
//        if(empty($alreadyShow)){
//
////            $query = [
////
////                'match_all' => new \stdClass()
////
////            ];
//            $query = [
//                'bool' => [
//                    'filter'=>[
//                        "term"=>[
//                            "gender"=>$gender == 1 ? 2 : 1 , //1=男显示女的 2=女的显示男的
//                        ],
//                    ],
//                ]
//            ];
//
//        }else{
//            //处理已经显示过的用户
//            $query = [
//                'bool' => [
//                    'must_not' => [
//                        'terms' => [
//                            'user_id' => explode(',',$alreadyShow),
//
//
//                        ]
//                    ]
//                ]
//            ];
//        }
//        $res = $this->EsSearch->getSearchData2('chat_friend_user','user',$limit,$page-1,$query);
//
//        if(!empty($res['data'])){
//
//            foreach($res['data'] as $k=>&$v){
//                unset($tagList);
//                $imgArr = json_decode($v['portrait'],true);
//                $v['portrait'] = array_map(function($key){return build_image($key);},$imgArr);
//                $v['birthday'] = date('Y-m-d',$v['birthday']);
//                $v['live_room_id'] = 0;
//                $v['is_online'] = 0;
//                if(!empty($v['tags'])){
//                    //标签信息
//                    $tagInfo = $this->userTagService->getTagNames(json_decode($v['tags'],true));
//                    foreach($tagInfo as $keys=>$tag){
//                        $tagList[] = ['name'=>$tag,'tag_id'=>$keys];
//                    }
//                    $v['tags'] = $tagList;
//                }else{
//                    $v['tags'] = [];
//                }
//                if(!empty($v['voice'])){
//                    $v['voice'] = build_url($v['voice']);
//                }
//            }
//            //储存已经显示过的用户
//            $user_ids = array_column($res['data'],'user_id');
//            $user_ids_str = implode(',',$user_ids);
//            if(!empty($alreadyShow)){
//                $user_ids_str = $user_ids_str.','.$alreadyShow;
//            }
//            Redis::set($this->userAlreadyShow.$userId,$user_ids_str);
//            Redis::expire($this->userAlreadyShow.$userId,3600*3);//3小时
//        }
//        $data['is_user_list'] = 1;
//        $data['list'] = $res['data'];
//        return $data;
//    }

}
